package com.j1ay.forum.handler;

import com.alibaba.fastjson.JSON;
import com.j1ay.forum.model.pojo.vo.ErrorCode;
import com.j1ay.forum.model.pojo.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author J1ay
 * @Date 2021/12/19 17:03
 * @Description 自定义认证失败类 -- 错误的账号或者密码
 */

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        returnFailure(httpServletResponse, e);
    }
    public void returnFailure(HttpServletResponse response, AuthenticationException e) throws IOException{
        System.out.println("===>" + e.getMessage());
        Result result;
        if (!Objects.isNull(e.getMessage())) {
            result = Result.fail(ErrorCode.ACCOUNT_PWD_NOT_TRUE.getCode(), e.getMessage());
        }
        else {
            result = Result.fail(ErrorCode.ACCOUNT_PWD_NOT_TRUE.getCode(), ErrorCode.ACCOUNT_PWD_NOT_TRUE.getMsg());

        }
        String json =  JSON.toJSONString(result);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
